CHAPTER 10 Part II

ANOTHER VISIT WITH THE CONTRACT PROGRAM
OR
WORKING WITH DYNAMICALLY SIZED LISTS
(continued)

VI. A (continued -click here to review part I)
Now that you are finished with your interface analysis, compare your conclusions with those below. Remember, that there are many possible 'correct answers' but some may be prettier, more efficient, or easier to use than others.

One of the things that you may have noticed is that as more properties are added, the output of those properties may need to be consolidated and organized more cleanly. One way to handle this might be to imagine a screen layout for the information on each contract. For example:

                                    Contract ID

    Contractee Name:     ..............................................


    Office Address:      ..............................................


                         ..............................................                       

                                                                        
The square footage:   ....................      The number of desks:   ..................


The number of days:   ....................      The per week charge:   ..................
Another thing you may have noticed is that it is getting awkward to input information for contract changes - if the user wants to make a large number of changes, it can take a while, not so much to enter the actual changes as that can't be avoided, but to make the requests. One way to speed things up is to have a menu as before but allow the user to enter at once the codes for all the fields to be changed. The menu might look as follows:

"Please enter the codes corresponding to the properties you want to change";

"Enter as many as you desire. When finished, hit Enter.";

You could not have written code to handle this before because you did not know how to handle strings. Now you are ready for the big time. One thing you might stop to consider at this point is just how important a good program interface is to the success of a piece of software. Just consider how you personally evaluate software. Of course, your criteria probably include issues involving windows and the use of input devices such as mice or joy sticks. We are avoiding those issues here but they are just variations on the theme.

All this is part of an improved program interface that needs to be incorporated into the program specifications. Now that we have come up with a better program interface, we move onto the class analysis. The question is: Have the changes we have made required any new classes be added to the program or do they simply require new or modified data and function members in existing classes? To answer this, the first step again is to underline and circle.

This time we come up with one new verb, 'includes', and five new nouns - 'information', 'person', 'name' (of the person), 'contractee', and 'address' (of the office).

The verb 'includes' and the noun 'information' can be ignored for the same reason we ignored the verb 'provided' in chapter 8 Again, we are dealing with English phrasing here. All programs deal with "information" and the act of 'including' information is a description of an action performed by almost all objects automatically - by having properties. In saying that contracts have or include certain information, the narrative is simply stating that instances of the class have certain properties (data members) but is saying nothing about the actions of contracts. As has already been said, object-oriented analysis and design is, in part, an art form requiring good common sense. You will become better at the process, the more you practice it, BUT whatever you do, make sure you use your own common sense.

The next noun is 'person'. Remember the issues here: Is 'person' a new element in the design? If so, is it a class or a property of some class? The answers to these questions require a careful analysis, an analysis that can be tricky. Using our common sense we say that persons exist as separate 'things'. They are not a property of some other thing. We are led to believe then that 'person' might be a new class in this program. However, look carefully at the problem. Does the problem concern itself in any way with persons other than as contractee's of contracts? In other words, do 'persons' exist separate from contracts? In this program it does not seem that they do. There are no actions or responsibilities uniquely related to persons and no properties of persons other than those related to contracts.

We could imagine a different problem where people 'existed' separate from contracts and performed actions or had their own responsibilities. For example, if the problem involved professional baseball players and each player-person had not only a contract but various properties related to baseball statistics we would need a separate class.

The upshot then is that 'person' in this problem narrative is another one of those words that we can ignore. In coming to this conclusion we can also say the same thing about 'contractee' since 'contractee's in this problem really are persons under a different name.

The final two words in the list (name and address) are important. They clearly refer to properties of a contract - each contract includes a name and an office address. Thus we have two more properties to add to our class declaration. We also have more member functions since these are properties that users of this class will want to access and modify. Note that an address really refers to a number of data items. While we could have one data member for the address that included the street address, the city, the state, and the zip code, it would be difficult then to only access one part of the address, for example, the state. Therefore, when we implement the address property we will actually create separate data members for each element of the address.

That completes our analysis as it relates to the 'Contract' class. Since we have not added any new behaviors, the CRC card remains the same. There are no new verbs related to the "ListOfContracts" class so its CRC card also remains the same.

It is now time to move to the implementation phase. As we do so, be aware that the analysis and design phases focus on what properties and responsibilities or behaviors are required in each class and say nothing about HOW those properties and responsibilities are implemented. We will discover that more changes need to be made than have been mentioned - primarily because of the way C++ handles strings.

B. Changes to the Contract Class Declaration - the New Properties
The analysis above indicated that we needed to add a number of new data members to the 'Contract' class. All of these are to be string variables. Each of these data members must also have 'Change...' and 'Provide...' member functions. Here are the changes to the class declaration starting with the declarations for the properties:

private:

int contractID;
int squareFootage;
int numberOfDaysPerWeek;
int numberOfDesks;

char* contracteeName;

char* officeStreetAddress;
// most complete addresses include space for a 2nd street address
// We will skip it here for simplicity

char* officeCity;
char* officeState;
char* officeZip;

We have five new properties - all strings. We could have declared some string type, for example:

typedef char String50[51];

and then declared all these data members to be of this type as in:

String50 contracteeName;

However, we have no idea how long these strings will be and Olympia does not use some form that limits the size of the name or other properties (We, of course, checked with her on this back in the analysis phase.) so it is safer to declare our strings with no limit on size. By declaring the properties as char pointers, we are not committing ourselves to any length. Of course, later we will need to request access memory for each of these strings but that is part of the definition so it can be ignored for now.

Notice how the address has been broken up into four separate strings. As already discussed this will allow a user program to access parts of the address. For example, some later program might need to access all contracts on "8th Street" for a special promotion.

Since the data member names are well chosen, we do not need comments with them. The one comment in this piece of code points out that there really should be a second street address field. For example, business addresses often include a department name or mail stop or room number in addition to a street address for the building. Another addition in this day of international business might be a Country name - although in an office cleaning program this might only make sense if Olympia lived in a border town. Anyway, all these details were ignored to keep the program simple. Once we know how to work with string types in general, adding more string variables is not a problem.


C. Changes to the Contract Class Declaration - the Constructors
Now we can look at the constructor declarations:


// Declaration of the class Contract - with a small set of strings
// File: contrct6.h

#ifndef CONTRACT_H
#define CONTRACT_H

class Contract
	{public:
		 Contract(int ID, int sqFootage, int numDesks, int numDays,
				     char* name,
				     char* oStreetAddress = "",   char* oCity = "",
				     char* oState = "",   char* oZip = "");
		/*
		Purpose:	To instantiate (create) an instance of the class 'contract'.
		Goal:		A new instance of class 'contract' now exists

		Inputs: 	NONE
		Outputs:	NONE
		Receives:	ID, Square Footage, Number of Desks, Number of Days 
					(All Integers)

					name, oStreetAddress, oCity, oState, oZip, oCountry 
					(All Strings)

		Returns:	 NONE
		*/


		Contract();
		/*
		Purpose:	To instantiate (create) an instance of the class 'contract' with
					default values.
		Goal:		A new instance of class 'contract' now exists

		Inputs: 	NONE
		Outputs:	NONE
		Receives:	NONE
		Returns:	NONE
		*/

		Contract(const Contract& c);
		/*
		Purpose:	To instantiate (create) an instance of the class 'contract' copying
					the values from another contract
		Goal:		A new instance of class 'contract' now exists

		Inputs: 	NONE
		Outputs:	NONE
		Receives:	A contract
		Returns:	NONE
		*/
The first constructor introduces a new aspect to parameter declarations. It is possible to provide default values to parameters in the parameter list itself. This is true for all functions not just constructors although it is the primary way this feature will be used here. If a value is not passed for a parameter and it has a default value, the parameter will use the default value anywhere the parameter is used in the function definition. Consider the following code fragment:


	// function declaration
	void SomeFunction(int amount, char* name = "Unknown"
				double cost = 10.00); 	  

	// function definition
	SomeFunction(int var1, char* name, double cost)	 
	{	cout << name << " bought " << amount  << " items for " << price;
	}
While this code has no real purpose, it is a good example of the use of default parameter values. The declaration includes default values for the second and third parameters. As you can see, this is accomplished by what looks like an assignment statement. Note that the function definition does not include the default values. Usually the first line of a definition looks the same as the declaration. Default values, however, are NOT included in the definition.

If this function is called with the line:

SomeFunction(3);

the output will be:

Unknown bought 3 items for 10.00

Since no value was passed for the parameters 'name' and 'cost', the default values were used. It would also be possible to have the following call:

SomeFunction(3, "Fred");

This time the output will be:

Fred bought 3 items for 10.00

Since the value 'Fred' was passed to the 'name' parameter, the default value of 'Unknown' is not used. The default value for 'cost' is, however, still used.

There are a number of restrictions on the use of default parameters based on the rules for how formal and actual parameters match up. As you may recall, the first actual parameter always becomes the value for the first formal parameter, the second for the second etc. Thus it is not possible in a call to 'SomeFunction' to provide a value for 'cost' and not provide a value for 'name'. Try to explain this to yourself before reading the next paragraph.

Consider the function call

SomeFunction(3, 12.95);

where the 12.95 is meant to be the cost of the items purchased. By the rule above, however, the system will attempt to place the value '12.95' in the formal parameter 'name' since '12.95' is the second actual parameter and 'name' is the second formal parameter. Obviously, 12.95 is not a name and C++ won't allow it anyway because 12.95 is not a string and 'name' expects a string value. In this case we are lucky because we will get an error message warning us of the problem. If the second formal parameter had also been of type double, we would not have gotten an error message and would not have noticed any problem until we carefully examined the output. (Of course, we always carefully examine the output of our test runs and some of those runs will include tests of any default parameter values.)

On the declaration side it would not be legal to write:

 
	void SomeFunction(double cost = 10.00, char* name = "Unknown"
				int amount); 
This declaration says that it is possible to leave out the cost and the name values in the parameters of a function call while passing an amount. However, consider the call:

SomeFunction(3);

where we want '3' to the the amount. If this code were legal, the system would copy the '3' to the parameter 'cost' (first to first) and would not have a value for 'amount' which does not have a default value. The end result would be the same type of error message you have most likely already seen when you failed to have the same number of formal and actual parameters and there were no default values. (In Borland C++ the error is "Too few parameters in call to …..")

The conclusion of this is that default parameters make certain function declarations possible but one must design the declaration carefully. All required parameters (those without defaults) must come first and those parameters with defaults must be ordered so that those least likely to be included in function calls come at the end of the parameter list.

In the case of the first constructor declaration for the 'Contract' class:

 
	Contract(int ID, int sqFootage, int numDesks, int numDays,
			char* name,
			char* oStreetAddress = "", char* oCity = "",
			char* oStat = "", char* oZip = "");
we have nine parameters - as programs become more complex, parameter lists can grow, especially in constructors. According to the program narrative, whenever a contract is created, the ID, square footage, number of desks, number of days, and the contractee's name must be provided. Therefore, these parameters do not have defaults. By the same token, the other properties do not need to be provided immediately so default values are provided for these. The default value was a blank. In other words, these will be empty strings. Note that it would not be possible to instantiate a contract where, for example, the zip code is provided but not the street address.

The second constructor declaration does not change. Technically, however, we could get rid of it completely if we rewrite the first constructor to include default values for ALL parameters. A function with default values for all parameters can be called with no actual parameters which, if you recall, was the original purpose of this second constructor. However, that would extend the 'power' of the first constructor past where we want and lose the distinction between those properties that must be provided immediately when a new contract is created and those that can wait as stated in the problem specifications.

There is a third constructor here, the so called copy constructor. This will be discussed in more detail below (Section F).

D. Changes to the Contract Class Declaration - the Destructor
The next change in the class declaration is the addition of a destructor. We noted above that a destructor was required for any class that includes pointers to arrays. More precisely, a destructor is needed for any class that includes any kind of pointer. Since strings in the 'Contract class are character pointers, we need a destructor for this class.

As we saw, it is easy to declare a destructor: one simply use the Class name preceded by a tilde. Thus the 'Contract' class destructor is declared as follows:

Contract:: ~Contract(); // destructor

E. The New Provide and Change Member Functions
Next come the 'Provide...' and 'Change...' member functions for the five new properties:

They are all essentially the same as other such functions. The 'Provide...' functions do not receive anything so they have no parameters and return the type of the property they refer to. In this case, they all return strings. The 'Change...' functions all receive a string - the new value of the property they refer to - and return nothing. As with the other string declarations in this file, all the strings here are declared as pointers to chars.

F. Special Member Functions Required to Handle Pointers
Finally, because we are implementing the strings with pointers, we need a new type of member function and a new variation of the constructor. Consider the following function definition:

 
	void SomeFunction(Contract c1 Contract c2);
	{	
		c2 = c1;
		// other processing
	}

We are not interested in why c1 is copied to c2 (via the assignment statement) but just that it is. When contracts did not include strings or other pointer type data members, this assignment worked just fine without any special handling. The square footage, number of desks, etc would get copied from 'c1' to 'c2'.

Exactly the same thing happens when data members include pointers only it is not what we probably want to happen! Since the data members that are pointers contain addresses, what gets copied is the addresses. In other words, both instances now point to the same memory for the strings and if the string is changed in one instance it is effectively changed in the other. Worse, if the class destructor is called for one of the instances (for example, because the instance is represented by a local variable), the memory used by its string data members is returned to the system even while that same memory is still being used by the other instance. Thus, the memory is both being used and is marked as available for other purposes. Later that returned memory could be requested and used for some completely different purpose - even while it is still being used by the still existing instance.

So, we need a special way to copy classes, such as 'Contract', with pointer-based data members. For that reason the following function declaration exists:

void CopyContract(Contract c);

Note that this function explicitly refers to only one contract. Remember that all member functions can be considered to be messages. In other words the code:

can be said to mean:

The member function 'CopyContract' might be used as follows:

c2. CopyContract(c1);

with the meaning:

The code for 'CopyContract' will make sure that the instance c2 uses separate memory for its strings.

********************

In addition to the 'CopyContract' function, we also need a new constructor - and for the same reason. When an instance of a class is passed by value, it is copied. That is what "pass by value" means. Thus, if we have the function declaration and call:

the instance c2 is copied to c1. But, we just saw that the copy operation has problems. Moreover, we can't handle these problems with the 'CopyContract' function we just declared since the copy that takes place in the function call here is implicit in the function call and is not something we have control over. In other words, there is no way to call 'CopyContract' to copy the parameter being passed.

To handle this C++ expects us to declare and define what is called the Copy Constructor:

Contract(const Contract& c);

It is no different from the other constructors we have declared except that it's sole parameter is a contract. This parameter represents the copy to be made when a function call passes an instance of 'Contract' by value. Note that the contract to be copied is passed by reference. If we remove the '&' symbol we are back to pass by value and we have not avoided any of the problems we are trying to deal with here.

When a function call passes a instance of 'Contract' by value, this constructor is called by the system. This constructor receives the contract (called 'c' here) being passed by value and instantiates a copy of that contract to be used as the local parameter.

At this point you may be a bit confused because you can't imagine what these two functions actually do. This is one time when the 'how' might clarify the 'what'. If you are confused, you might just wait until after you read the discussion on 'how' in the next section.

That completes the discussion of changes to the Contract class declaration. The full code for the declarations is in the file "contrct6.h"

IX. Defining the Member Functions for the Contract class
The changes we will examine here are all due to the addition of the string properties. In addition they are somewhat repetitious because we perform the same basic set of operations over and over on the different strings. For that reason not all of the changes will be explicitly discussed here. The complete code is under the file name "contrct6.cpp"

A. The Constructors
We begin with a look at part of the first constructor:


Contract::Contract(int ID, int sqFootage, int numDesks, int numDays,
			char* name, char* oStreetAddr, char* oCity,
			char* oState, char* oZip)
{  	contractID = ID;
	squareFootage = sqFootage;
	numberOfDesks = numDesks;
	numberOfDaysPerWeek = numDays;

	int len = strlen(name);
	contracteeName = new char[len + 1];
	strcpy(contracteeName, name);

	len = strlen(oStreetAddr);
	officeStreetAddress = new char[len + 1];
	strcpy(officeStreetAddress,oStreetAddr);

	len = strlen(oCity);
	officeCity = new char[len + 1];
	strcpy(officeCity,oCity);

	len = strlen(oState);
	officeState = new char[len + 1];
	strcpy(officeState,oState);

	len = strlen(oZip);
	officeZip = new char[len + 1];
	strcpy(officeZip,oZip);
}
Note that the parameter list does not include the default values. They are only included in the declarations. The code to assign the string parameters to the various string data members follows a consistent format. The length of the string parameter is found; enough memory for a string of that size (plus 1 for the null character) is requested, and its address assigned to the corresponding data member. Finally 'strcpy' is used to copy one string to the other.

The second constructor is the same with all the strings automatically made to be empty.


Contract::Contract()
{  contractID = 0;
	squareFootage = 0;
	numberOfDesks = 0;
	numberOfDaysPerWeek = 0;

	contracteeName = new char[1];
	strcpy(contracteeName, "");

	officeStreetAddress = new char[1];
	strcpy(officeStreetAddress,"");

	officeCity = new char[1];
	strcpy(officeCity,"");

	officeState = new char[1];
	strcpy(officeState,"");

	officeZip = new char[1];
	strcpy(officeZip,"");
}
Since all the strings are empty, the are represented by one element arrays - just enough room for the null character.

Now let's take a look at the code for the copy constructor.


Contract :: Contract(const Contract& c)
{	int len = strlen(c.contracteeName);
	contracteeName = new char[len + 1];
	strcpy(contracteeName, c.contracteeName);

	len = strlen(c.officeStreetAddress);
	officeStreetAddress = new char[len + 1];
	strcpy(officeStreetAddress,c.officeStreetAddress);

	len = strlen(c.officeCity);
	officeCity = new char[len + 1];
	strcpy(officeCity,c.officeCity);

	len = strlen(c.officeState);
	officeState = new char[len + 1];
	strcpy(officeState,c.officeState);

	len = strlen(c.officeZip);
	officeZip = new char[len + 1];
	strcpy(officeZip,c.officeZip);

	contractID = c.contractID;
	squareFootage = c. squareFootage;
	numberOfDaysPerWeek = c.numberOfDaysPerWeek;
	numberOfDesks = c.numberOfDesks;
}

Remember, the purpose of this is to deal with the string properties. The other properties are dealt with via straight assignment statements as is shown in the last four lines of this function. To copy the strings we write essentially the same code we saw in the first constructor. Consider the code to copy the contractee name. First, the code gets the length of the name to be copied:

int len = strlen(c.contracteeName);

Note that since this constructor is a member function of 'Contract' it has access to the data members of any instance of 'Contract' including 'c'. Also, note that since 'c' is not the instance that was sent the message but, instead, was passed as a parameter, we must use the syntax 'c.contracteeName'. In other words, the code is referring explicitly to the name field of the instance 'c'. If we dropped the 'c' we would be referring to the instance that was sent the message - the one that will receive the coped data.

We have seen this dot notation used before in function calls but not with data members. Up to now we have not needed to access the data members of one instance of a class while working with a different instance of the same class. Instead, the code that needed access to the data members of an instance was not part of any member function and, therefore, had to use the public member functions of the class in question. Since data members usually are declared in the private part of a class declaration, they are unknown outside the class and cannot be directly accessed by code using the class. To repeat: it is legal to use the dot notation with a data member of the 'Contract' class here because this function is a member of the 'Contract' class and thus has access to the data members of all instances of the class.

Once we have the length, we request enough memory for that many characters plus 1 and assign the address to 'contracteeName'. This time we do not place the 'c.' in front of the data member name because we are referring to the new instance being created not to the instance from which we are getting the data for this new instance.

Finally, we make the copy using 'strcpy'. Note that here we use both 'contracteeName' by itself and with the 'c.'. In other words, we are copying the contents of 'c.contracteeName' to the 'contracteeName data member of the new instance.

You will see that all the other string properties are handled the same way. Not only that, but the code for the 'CopyContract' member function is the same. It may seem strange that we need the same code in multiple places. The reason is that these functions have different purposes: one is a constructor, the other is used to copy from one existing instance to another. Any smart coder will not type this code twice. Instead he or she will use the copy and paste features of the editor extensively. When this code was written, the author first wrote the first constructor. Then he copied the code to the copy constructor and removed the 'if' statements that checked to see if the default values had been used. He added the dot notation and he was finished with the copy constructor. Then he copied this code to the 'CopyContract' function and had three 'complex' functions finished in no time.

B. The Destructor
We now move to the destructor. There are five arrays being pointed to by data members of the class so we need five delete operations:


Contract :: ~Contract()
{	delete [] contracteeName;
	delete [] officeStreetAddress;
	delete [] officeCity;
	delete [] officeState;
	delete [] officeZip;
}
Remember that the [] is needed because each of these data members points to an array.

C. The Rest of the Function Members

The 'Provide...' and 'Change...' member functions are all similar to each other except for the parameter and data member names used. We will examine 'ProvideOfficeCity' and 'ChangeOfficeCity' here:


char* Contract:: ProvideOfficeCity()
{	return officeCity;
}

void  Contract:: ChangeOfficeCity(char* city)
{	delete [] officeCity;  			// delete the whole string array
	int len = strlen(city);
	officeCity = new char[len + 1]; 	// don't forget the null char
	strcpy(officeCity, city);
}
As with all 'Provide...' functions this one simply returns the contents of the appropriate data member, 'officeCity'.

'ChangeOfficeCity' is a bit more complex. We are changing the string contents of the 'officeCity' field and we don't know how much memory will be required for the new string. The easiest way to handle this is to return the memory used by the old string and then request just the amount of memory required for the new string. To return the memory, the first line of the function is

delete [] officeCity;

The rest of the code is exactly what we have done with every other string assignment. In fact, this code was also copied from elsewhere and modified to fit the variable names used here.

There is quite a bit of code to this modified version of the definitions for 'Contract'. As noted, however, much of it is quite repetitive and easily copyable. The trick in code like this is to understand what needs to be done and then figure out how to do it as easily as possible using the capabilities of your editor. Again, for the complete code check out contrct6.cpp

X. ListOfContracts and the Main Program
Notice that our modified version of the problem narrative made no mention of changes to the 'ListOfContracts' class. We are only adding strings and those additions have no effect on the list itself so there are no changes to the .h or .cpp files for this class except to change the include statement to include the new version of the 'Contract' class header file, contrct6.h. The files with those few changes are called ch10lst1.h and ch10lst1.cpp.

However, there are changes to the main program - mostly because of the changes to the interface we worked out in the analysis phase above. Here is where we use the string input operations we learned earlier. The changes in the input interface are more complex so let's start with them.

When a user selects the option to change contract information, the function 'ChangeInfo' is called. The original algorithm for this function repeatedly asked the user for a property code (a character) until a 'N' was entered to indicate that no more property values were to be changed. For each valid property code entered, the user was asked for the new value and the change was made.

Our analysis of this interface indicated that it would be faster if the user was allowed to enter all the codes for changes at once. Now that we know how to work with strings, we have a data structure that will allow us to do this. We will use a function called 'GetProperties' to retrieve the codes entered. However, instead of returning simply a character, this function will return a string.

We will explore how to implement this function in a bit but first let's continue our discussion of 'ChangeInfo'. Once the function has a string of codes, it needs to execute a loop to process the codes. The old loop continued until an 'N' was entered and we could continue to force the user to enter an 'N' in the new version. However, strings have their own natural ending symbol, the null character. Thus, we can write the loop to continue until the '\0' symbol is encountered in the string of codes.

Inside the loop in the old version there was a switch statement for each of the properties and separate calls to functions to get the new values. For example, there was the function ' GetSquareFootage' to ask the user for a new value for the square footage of an office and a function 'GetNumDesks' to get the new value for the 'numDesks' data member. As we add more properties, this is going to get ugly real fast. Unfortunately, we still need the switch statement itself to process the different codes but we can avoid having to create unique value requesting functions for each property. Instead we will create a general purpose input function for all the new string properties. This function will allow us to ask the user for the value of a specific property by passing in the name of that property. It will return the new string value for that property.

Here is the function definition for this function:

It has two string parameters. The first parameter will be used to return the new value while the second will be used to receive and output the name of the property to be changed. Note how the 'cout' line uses this second parameter. For example, if the string 'Street Address' is passed in, the screen will display:

"Please enter the new Street Address"

If one wanted completely unique prompts, one could pass in the whole prompt and rewrite the cout line simply as:

cout << property << endl;

The third line of this function represents the first time we have used the 'get' input function we learned earlier in this chapter. 'Get(string, 81)', as you may recall, will read until it encounters an newline symbol or up to 80 characters - the 81st character is for the '\0'. Thus the user can type any length of string he or she wants up to 80 characters. The code is written 'cin.get(....)' because 'get' is actually a member function of the class istream of which 'cin' is an instance.

Unlike the '<<' operator, the 'get' member function does not skip white space or newline characters before reading in data. Nor, does it actually read the newline character when it encounters it. Thus, if the system has used the 'get' function and encountered a newline character, that newline character remains in the input stream. Therefore, the next 'get' will again encounter that newline character and stop immediately without reading anything! To avoid this we include the second line:

cin.ignore(80, '\n');

As the comment says, this skips past ("consumes") any left over characters until it has skipped over 80 characters or the newline character. In our program there is unlikely to be an left over characters but there will be newlines left over from previous inputs. With the newline out of the way, the next 'get' function will operate safely.

As an aside, here you see another function that is so general it is really a pattern. You can use this approach of passing a string that represents part or all of an output anywhere you want to use one function to generate multiple different outputs.

We return now to 'ChangeInfo'. Since the ' GetNewString' function we just discussed returns a string, it cannot be used to retrieve new values for the integer based properties. We could write one function that would return an integer but the separate functions for these properties already exist so we will continue to use them. What we will change is the codes for these properties. We could easily make up codes that somehow matched the properties when we had only a few properties but as the number of properties have grown, too many of the property names have started with the same letter. Therefore the codes have been changed. It so happens that we only have eight properties so the codes 1-8 work just fine. If we had more properties, we would have to start using letter codes. We can't use a code such as '10' because the combined set of codes entered are stored as a string and the program would interpret this is the separate codes '0' and '1'.

Here is the C++ code based on this discussion:


void 	ChangeInfo( Contract& contract)
{  String80 string;
	String80 properties;
	GetProperties(properties);
	int index = 0;
	while (properties[index])
	{	switch (properties[index])
		{  case '1':
				GetNewString(string, "ContracteeName");
				contract.ChangeContracteeName(string);
				break;

			case '2':
				GetNewString(string, "Office Street Address");
				contract.ChangeOfficeStreetAddress(string);
				break;
			case '3':
				GetNewString(string, "Office City");
				contract.ChangeOfficeCity(string);
				break;
			case '4':
				GetNewString(string, "Office State");
				contract.ChangeOfficeState(string);
				break;
			case '5':
				GetNewString(string, "Office Zip Code");
				contract.ChangeOfficeZip(string);
				break;
			case '6':
				int sqFootage;
				sqFootage = GetSquareFootage();
				contract.ChangeSquareFootage(sqFootage);
				break;
			case '7':
				int numDesks;
				numDesks = GetNumDesks();
				contract.ChangeNumDesks(numDesks);
				break;
			case '8':
				int numDays;
				numDays = GetNumDays();
				contract.ChangeNumDays(numDays);
				break;
			default:
				cout << endl << properties[index] << " is an invalid code.\n";

		}  // end switch
		index++;
	} // end while
	clrscr();
	DisplayInfo(contract); // allow user to see changes before proceeding
}
The function 'GetProperties' retrieves at once all the properties to be changed and then the loop processing begins. Just for the heck of it, this code is written using a while loop. A 'for' loop would have worked just as well.

We want to begin by looking at the first element of the string array ' properties'. Since a while loop does not have a special mechanism to initialize variables, the line:

int index = 0;

comes right before the loop begins. This variable will be used as an index into the array, allowing the code to examine the individual characters in the string one by one.

Examine the test condition for the while loop:

while (properties[index])

Recall that the character '\0' is equivalent to the integer value 0 and therefore it is equivalent to FALSE. (In contrast, the character '0' has an ASCII code whose integer equivalent is 48!). Therefore, this while loop will continue to execute until the NULL character appears in the string.

Inside the loop is a switch statement that allows the program to perform the appropriate instructions for each of the property codes. For example, if property code 3 appears in the string, the program will call the function 'GetNewString' passing the string "Office City". When 'GetNewString' returns with the new value for the office city, the member function 'ChangeOfficeCity' is called for the contract in question and the value of the office city property is changed. Note that the very last line of the while loop increments the index variable to insure that the program examines the next character in the string.

The last two lines of the function are a bonus. First, the screen is cleared and then the code displays the new property values for the contract. Strictly speaking, this is not part of the interface we have developed but it does make sense to display the changes in case some mistake was made.

That finishes this discussion except for the code for the function 'GetProperties'. As usual when we use functional decomposition to break our code up into small, manageable functions, the code for this function is relatively simple. The algorithm has two lines:

Display the Menu of Property Codes
Read in the codes entered by the user.

You have written the code to display a menu many times by now and we just saw how to read in a stream of characters (the characters entered by the user) using the 'get' member function. We also saw that it is wise to use the 'ignore' member function before using 'get'. Given all this, the following code should come as no surprise:


void GetProperties(String80 properties)
{  	cin.ignore(80, '\n');
	cout << "Please enter the codes corresponding to the properties you want to "; 
	cout << "change\n";
	cout << "Enter as many as you desire. When finished, hit Enter.\n";

	cout << "          '1':  Contractee Name\n";
	cout << "          '2':  Office Street Address\n";
	cout << "          '3':  Office City\n";
	cout << "          '4':  Office State\n";
	cout << "          '5':  Office Zip\n";
	cout << "          '6':  square Footage\n";
	cout << "          '7':  number of desks\n";
	cout << "          '8':  number of days per week\n";
	cin.get(properties,81);
}
As with 'GetNewString' the user will type any length string he or she desires - representing the codes for as many properties as need to be changed. When finished, the user hits the 'Enter' key, the program stops reading from the input stream and the function returns. Note that since the string value is returned via a parameter, there is no reason for an explicit return statement.

The code to add a new contract is also affected by this new interface, at least by the new string properties. There are more complex ways of modifying the code for this option (See Exercise ???) but one simple way is simply to add repeated calls to 'GetNewString' passing the appropriate property name string. Here then is the code:



void CreateContract(int contractID, Contract& contract)
{  String80 string;
	contract.ChangeID(contractID);

	GetNewString(string, "ContracteeName");
	contract.ChangeContracteeName(string);

	GetNewString(string, "Office Street Address");
	contract.ChangeOfficeStreetAddress(string);

	GetNewString(string, "Office City");
	contract.ChangeOfficeCity(string);

	GetNewString(string, "Office State");
	contract.ChangeOfficeState(string);

	GetNewString(string, "Office Zip Code");
	contract.ChangeOfficeZip(string);

	int sqFootage;
	sqFootage = GetSquareFootage();
	contract.ChangeSquareFootage(sqFootage);

	int numDesks;
	numDesks = GetNumDesks();
	contract.ChangeNumDesks(numDesks);

	int numDays;
	numDays = GetNumDays();
	contract.ChangeNumDays(numDays);

	clrscr();
	DisplayInfo(contract);
}
******************

Changes will also have to be made to the function 'InitializeInstances' to handle the new string properties. These, however, simply involve calls to the new member functions for changing the values of the new properties. The first contract created in the present version of this function has contract ID '1234'. To provide a contractee name for this contract one would simply call the member function 'ChangeContracteeName' with the string constant of the name to be included. The code might be:

contract.ChangeContracteeName("Freddy Smith");

The same approach will work for all the other properties as you can see by examining the code in the file ch10tst1.cpp.

The only other changes required in this program are in the function 'DisplayInfo' - the new string properties need to be output and we earlier decided to streamline the form of that output. Unlike string input and manipulation which required serious modifications to the code, string output is simple. As noted earlier, we have already been doing string output in the form of prompts and other messages. The only difference is that now we are working with string variables instead of string constants. For that reason the code is self explanatory and you should simply review the file ch10tst1.cpp.

After you are comfortable with the code in that file, you should compile, link, and run the complete program. The files you will need are:

That completes this chapter. You have learned a lot in the last two chapters:

Probably string handling - inside and outside of classes - was the hardest part of this material. You may be pleased to know (and frustrated that you were not told sooner) that the newer versions of C++ include a standard string class that builds in many of the details we had to explicitly code. Why weren't you told sooner? Well, what you learned here can be applied to other situations. As a matter of fact, if we were faced with a program, for example, that dealt with multiple different lists and a class that included them all, we would have to write exactly the kind of code you wrote here.

Anyway, if you want to use this new class, there is information in the "C++ Essentials" document. You should also check out your compiler manual for references to the 'string' class. Once you include the appropriate header file - look for the file name "cstring.h"- you should be able to declare variables of type 'string'. (As you have learned, if the class name is 'string', then there is a new type called 'string'.) Review the public member functions and constructor descriptions in your manual for more information on the many ways variables of this type can be used.